/**
  ETFAna project, Anyang Normal University && IMP-CAS
  \class ETFTrack
  \brief class for a post-Mag track, i.e. track downstream of the dipole magnet
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2021-11-04
  \date 2024-01-09 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2021-11-04   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <iostream>
#include <cstring>
#include "ETFTrack.h"
#include "ETFDetector.h"
#include "ETFMsg.h"

using std::cout;
using std::endl;

ETFTrack::ETFTrack() : ETFVTrack(){
  // TODO: user input configuration expected here
  fChiPD = 2.6; // in mm
  Initialize();
} // end ctor

// copy ctor
ETFTrack::ETFTrack(const ETFTrack &t) : ETFVTrack(t){
  *this = t;
} // end copy ctor
// assignment ctor
ETFTrack &ETFTrack::operator=(const ETFTrack &t){
  if(&t == this) return *this;

  copy(&t);

  return *this;
} // end assignment ctor

// the same as copy ctor
void ETFTrack::copy(const ETFVTrack *t){
  ETFVTrack::copy(t);

  const ETFTrack *p = static_cast<const ETFTrack *>(t);
  fFiredStripId = p->fFiredStripId;
  fNStripStray = p->fNStripStray;
  f3DId = p->f3DId;
} // end member function Copy

ETFTrack::~ETFTrack(){}

void ETFTrack::Initialize(){
  ETFVTrack::Initialize();
  fFiredStripId = -1;
  fNStripStray = -999.;
  f3DId = -1;
} // end member function Initialize

// assign hit pos at det's central plane
void ETFTrack::UpdateHitPos(ETFDetector *d){
  const string name = d->GetName();
  const double p1[2] = {GetK(), GetB()};
  d->GetHitPositionL(p1, fHitPosMap[name]);
} // end member function UpdateHitPos

int ETFTrack::EnoughHit(){
  return EnoughHit(fHits);
} // end member function EnoughHit

// a static version
int ETFTrack::EnoughHit(const map<int, ETFDCHit *> &hits){
  int n = 0; // number of valid hits
  for(auto &p : hits) if(p.second) n++;
  if(n >= 4) return n;
  if(n < 3) return 0;

  bool normal = true; // at least one hits exists in each of the 3 DCs
  for(int i = 3; i--;) normal = (hits.at(2*i) || hits.at(2*i+1)) && normal;
  return normal ? n : 0;
} // end member function EnoughHit

void ETFTrack::SetId(int id, short type){
  const char xuv[] = {'X', 'U', 'V'};
  fName = ETFMsg::Form("Track%c #%d", xuv[type%3], id);
} // end member function SetId

void ETFTrack::Print(const char *) const{
  ETFVTrack::Print();
  cout << "fFiredStripId: " << fFiredStripId;
  cout << " fNStripStray: " << fNStripStray << endl;
  cout << "f3DId: " << f3DId << endl;
} // end member function Print
